//
//  ResultView.m
//  MobileZIPCodes
//
//  Created by Andreas Schwelling on 02.12.07.
//	http://www.andi.de/zipcodes/
// 
//  Released under the GNU General Public License.
//  See LICENSE for details.
//
//  Use at your own risk.
//

#import "ResultView.h"



@implementation ResultViewPrefTable 

- (BOOL) canDeleteRow:( int)row {
	//NSLog(@"canDeleteRow: %d",row);
	if (row == _delable && _delable != 0) return YES; else return NO;
}

- (BOOL) shouldIndentRow: (int) row {
	//NSLog(@"shouwIndentRow");
	return NO;
}

- (BOOL)canInsertAtRow:(int)row {
	if (row == _insertable && _insertable != 0) return YES; else return NO;
}

-(void)setDeletable:(int)nr {
	_delable = nr;
}

-(void)setInsertable:(int)nr {
	_insertable = nr;
}

@end

@implementation SearchNameResultView


-(id)initWithFrame:(CGRect)rect
{
	
	//NSLog(@"zipcodearr: %@",_zipcodes);
	
	_zipcodes = [[NSMutableArray alloc] init];
	
	_numberofzipcodegroups = ([_zipcodes count] / 3) + ([_zipcodes count] % 3);
	
	//NSLog(@"zipcode groups: %d",_numberofzipcodegroups);
	
	
	self = [super initWithFrame:rect];
	
	
	_table = [[ResultViewPrefTable alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-49.0f)];
	[_table setDataSource:self];
	[_table setDelegate:self];
	[_table setDeletable:0];
	[_table setInsertable:0];
	[_table enableRowDeletion:YES animated:YES];
	
	
	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    float transparentComponents[4] = {0, 0, 0, 0};
    float grayComponents[4] = {0.85, 0.85, 0.85, 1};
    
    float foreground[4] = {0.25, 0.22, 0.25, 1};
	
    CGColorSpaceRef colorShadow = CGColorSpaceCreateDeviceRGB();
	CGSize size;
    size.height = 1;
    size.width = 1;
    
    
	UITextLabel *text;
    text  = [[UITextLabel alloc] initWithFrame:
			 CGRectMake(15.0f, 15.0f, 160.0f, 20.0f)];
    [ text setShadowColor: CGColorCreate(colorShadow, grayComponents)];
    [ text setShadowOffset: size ];
    [ text setText:@"Location"];
    [ text setColor: CGColorCreate(colorSpace, foreground)];
	struct __GSFont* font = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:0 size:16];
    [ text setBackgroundColor:
	 CGColorCreate(colorSpace, transparentComponents)];
    [ _table addSubview: text ];
    [ text release ];
	
    text  = [[UITextLabel alloc] initWithFrame:
			 CGRectMake(15.0f, 100.0f, 160.0f, 20.0f)];
    [ text setShadowColor: CGColorCreate(colorShadow, grayComponents)];
    [ text setShadowOffset: size ];
    [ text setText:@"Details"];
    [ text setColor: CGColorCreate(colorSpace, foreground)];
	
    [ text setFont: font];
	// CFRelease(font);
    [ text setBackgroundColor:
	 CGColorCreate(colorSpace, transparentComponents)];
    [ _table addSubview: text ];
    [ text release ];
	
	_favourstr = @"Add to favourites";
	
	[_table reloadData];
	
	[self addSubview:_table];
	
	_uiphud = [[UIProgressHUD alloc] initWithFrame:  CGRectMake(80.0f, 110.0f, 160.0f, 120.0f)];
	[_uiphud setText: @"Loading..."];
	//	[_uiphud drawRect: rect];
	[_uiphud show: YES];
	
	[self addSubview:_uiphud];
	
	//	[NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(loadData:) userInfo:nil repeats:NO];
	
	//NSLog(@"d: %@",[td getDescription]);
	return self;
}

- (void) dealloc {
	
	[_table release];
	[_zipcodes release];
	[super dealloc];
}

-(void)setCity:(NSString*)city {
	_city = city;
	[_city retain];
}

-(void)setState:(NSString*)state {
	_state = state;
}

-(void)setCountry:(NSString*)country {
	_country = country;
}

- (void) fetchData {
	[[NSTimer scheduledTimerWithTimeInterval:0.75 target:self selector:@selector(buildContent:) userInfo:nil repeats:NO] retain];
	
}


-(void) buildContent:(id)p {
	
	DataManager *dm = [DataManager alloc];
	
	SQLiteDB *sql = [[SQLiteDB alloc] initWithPath:[dm getDataBaseName:_country]];
	
	
	
	
	
	
	NSArray *nsa = [sql query:[NSString stringWithFormat:@"select c.city, s.state, z.zipcode, a.add1 from relations r, city c, states s, zipcodes z, addendum1 a where r.cityid = c.id and r.stateid = s.id and r.zipid = z.id and r.add1id = a.id and c.city like '%@' and s.state like '%@' group by r.zipid order by z.zipcode;",_city,_state]];
	//NSLog(@"array: %@",nsa);
	
	_state = [ NSString stringWithFormat: @"%@", [[nsa objectAtIndex:0] objectForKey:@"state"] ];
	[_state retain];
	//NSLog(@"state: %@",_state);
	_addendum1 = [[ NSString stringWithFormat: @"%@", [[nsa objectAtIndex:0] objectForKey:@"add1"] ] capitalizedString] ;
	[_addendum1 retain];
	
	
	//[_zipcodes release];
	_zipcodes = [[NSMutableArray alloc] init];
	
	int i=0;
	for (i=0;i<[nsa count];i++) {
		
		NSString *zipstr = [ NSString stringWithFormat: @"%@", [[nsa objectAtIndex:i] objectForKey:@"zipcode"] ];
		
		[_zipcodes addObject:zipstr];
		//		NSLog(@"obj: %@", zipstr);
	}
	[_zipcodes retain];
	
	_numberofzipcodegroups = ([_zipcodes count] / 3) + ([_zipcodes count] % 3);
	
	if ([dm isFavouredEntry:_city forCountry:_country]) {
		
		//NSLog(@"fav entry");
		_isfavoured = YES;
		
		[_table setDeletable:(12+_numberofzipcodegroups)];
		[_table setInsertable:0];
		_favourstr = @"Remove from favourites";
		
		
	} else {
		[_table setInsertable:(12+_numberofzipcodegroups)];
		[_table setDeletable:0];
		_isfavoured = NO;
		
	}
	[dm release];
	[sql release];
	
	[_table reloadData];
	[_uiphud show: NO];
	[_uiphud removeFromSuperview];
	[_uiphud release];
	
}


-(void)setDelegate:(id)del {
	//NSLog(@"delegate: %@",del);
	_delegate = del;
}



-(void)setPrevView:(UIView*)pv {
	_prevView = pv;
}

-(UIView*)getPrevView {
	return _prevView;
}

#pragma mark - delegated methods -

- (int)numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table
{
	return 7;
}


- (float)preferencesTable:(UIPreferencesTable *)table 
			 heightForRow:(int)row 
				  inGroup:(int)group 
	   withProposedHeight:(float)proposed 
{
	if (group == 0 || group == 2) {
        return 10;
    }
	
	
    return proposed;
}


- (int)preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group
{
	switch (group)
  {
	  case 0: return 1;
	  case 1: return 1;
	  case 2:	return 1;
	  case 3: return 3;
	  case 4: return _numberofzipcodegroups;
	  case 5: return 1;
	  case 6: return 1;
		  
		  
  }
}

- (UIPreferencesTableCell *)preferencesTable:(UIPreferencesTable *)table cellForGroup:(int)group
{
	UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
	
	return [cell autorelease];
}

- (UIPreferencesTableCell *)preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group
{
	
	if (group == 0 || group == 2)
	  {
		  
		  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
		  [cell setTitle:@""];
		  [ cell setDrawsBackground: NO ];
		  return [cell autorelease];
	  }				
	else if (group == 1)
	  {
		  
		  
		  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
		  [cell setTitle:[_city capitalizedString]];
		  [cell setAlignment:2];
		  
		  return [cell autorelease];
		  
		  
		  
	  } 
	else if (group == 3) 
	  {
		  switch (row)
		{
			case 0:
		  {
			  UIPreferencesTableCell *statecell = [[UIPreferencesTableCell alloc] init];
			  [statecell setTitle:@"State"];
			  [statecell setValue:_state];
			  
			  //[statecell setAlignment:citycellAlign];
			  
			  return [statecell autorelease];
		  }
			case 1:
		  {
			  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
			  [cell setTitle:@"Country"];
			  [cell setValue:_country];
			  [cell setUsesBlueDisclosureCircle:YES];
			  
			  return [cell autorelease];
		  }
			case 2:
		  {
			  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
			  [cell setTitle:@"County"];
			  [cell setValue:_addendum1];
			  [cell setUsesBlueDisclosureCircle:YES];
			  
			  return [cell autorelease];
		  }
		}
	  } 
	else if (group == 4) 
	  {
		  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
		  
		  if (row == 0) {
			  [cell setTitle:@"ZIP code(s)"];
		  } else {
			  [cell setTitle:@" "];
		  }
		  
		  int begin = (row * 3) + 1;
		  
		  int end = (row * 3) + 3;
		  
		  if (end>[_zipcodes count]) end = [_zipcodes count];
		  
		  NSString *valstr = @"";
		  
		  int i=0;
		  for (i=begin-1;i<end;i++) {
			  valstr = [[valstr stringByAppendingString:[_zipcodes objectAtIndex:i]] stringByAppendingString:@" "];
		  }
		  
		  [cell setValue:valstr];
		  
		  
		  return [cell autorelease];
	  }	
	else if (group == 5) 
	  {
		  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
		  [cell setTitle:_favourstr];
		  [cell setAlignment:2];
		  return [cell autorelease];
	  }
	
	else if (group == 6) 
	  {
		  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
		  [cell setTitle:@"Show in Maps"];
		  [cell setShowDisclosure:YES];
		  [cell setAlignment:2];
		  return [cell autorelease];
	  }
	
}

- (void)tableRowSelected:(NSNotification *)notification
{
	
	
	if ([_table selectedRow] == (14 + _numberofzipcodegroups))
	  {
		  
		  
		  NSString *urlstring = [NSString stringWithFormat:@"http://maps.google.com/?q=%@ %@ %@",_city, _state,_country];
		  NSString *fixedURL = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)urlstring, NULL, NULL, kCFStringEncodingUTF8);
		  
		  MobileZIPCodesApp *mzca = [MobileZIPCodesApp sharedInstance];
		  
		  [mzca openURL:[NSURL URLWithString:fixedURL]];
	  }	
	
}


- (BOOL) table:(UITable *) table canSelectRow:(int) row 
{
	if ( row == (14 + _numberofzipcodegroups)) return YES; else return NO;
}


- (void)table:(UITable*)table deleteRow:(int)row {
	// the remove code
	//[activesArray removeObject:[NSString stringWithFormat:@"%d",row]];
	//NSLog(@" detelet: %d",row);
	
	_isfavoured = NO;
	
	[_table setDeletable:0];
	[_table setInsertable:12+_numberofzipcodegroups];
	_favourstr = @"Add to favourites";
	
	DataManager *dm = [DataManager alloc];
	
	[dm removeFavouredEntry:_city  forCountry:_country];
	
	[dm release];
	
	
	[_table reloadData];
}


- (void) table:(UITable *) table insertAtRow:(int) row 
{
	//NSLog(@" insertrow: %d",row);
	
	_isfavoured = YES;
	
	[_table setDeletable:12+_numberofzipcodegroups];
	[_table setInsertable:0];
	_favourstr = @"Remove from favourites";
	
	
	DataManager *dm = [DataManager alloc];
	
	[dm addFavouredEntry:_city withState:_state forCountry:_country];
	
	[dm release];
	
	[_table reloadData];
	
    
}



@end










@implementation SearchZipResultView


-(id)initWithFrame:(CGRect)rect
{
	
	self = [super initWithFrame:rect];
	
	
	_table = [[ResultViewPrefTable alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-49.0f)];
	[_table setDataSource:self];
	[_table setDelegate:self];
	[_table setInsertable:13];
	[_table enableRowDeletion:YES animated:YES];
	
	
	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    float transparentComponents[4] = {0, 0, 0, 0};
    float grayComponents[4] = {0.85, 0.85, 0.85, 1};
    
    float foreground[4] = {0.25, 0.22, 0.25, 1};
	
    CGColorSpaceRef colorShadow = CGColorSpaceCreateDeviceRGB();
	CGSize size;
    size.height = 1;
    size.width = 1;
    
    
	UITextLabel *text;
    text  = [[UITextLabel alloc] initWithFrame:
			 CGRectMake(15.0f, 15.0f, 160.0f, 20.0f)];
    [ text setShadowColor: CGColorCreate(colorShadow, grayComponents)];
    [ text setShadowOffset: size ];
    [ text setText:@"ZIP code"];
    [ text setColor: CGColorCreate(colorSpace, foreground)];
	struct __GSFont* font = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:0 size:16];
    [ text setBackgroundColor:
	 CGColorCreate(colorSpace, transparentComponents)];
    [ _table addSubview: text ];
    [ text release ];
	
    text  = [[UITextLabel alloc] initWithFrame:
			 CGRectMake(15.0f, 100.0f, 160.0f, 20.0f)];
    [ text setShadowColor: CGColorCreate(colorShadow, grayComponents)];
    [ text setShadowOffset: size ];
    [ text setText:@"Details"];
    [ text setColor: CGColorCreate(colorSpace, foreground)];
	
    [ text setFont: font];
	// CFRelease(font);
    [ text setBackgroundColor:
	 CGColorCreate(colorSpace, transparentComponents)];
    [ _table addSubview: text ];
    [ text release ];
	
	_favourstr = @"Add to favourites";
	
	[_table reloadData];
	
	[self addSubview:_table];
	
	_uiphud = [[UIProgressHUD alloc] initWithFrame:  CGRectMake(80.0f, 110.0f, 160.0f, 120.0f)];
	[_uiphud setText: @"Loading..."];
	//	[_uiphud drawRect: rect];
	[_uiphud show: YES];
	
	[self addSubview:_uiphud];
	
	//	[NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(loadData:) userInfo:nil repeats:NO];
	
	//NSLog(@"d: %@",[td getDescription]);
	return self;
}

- (void) dealloc {
	
	[_table release];
	[super dealloc];
}

-(void)setZipcode:(NSString*)zipcode {
	_zipcode = zipcode;
	[_zipcode retain];
}


-(void)setState:(NSString*)state {
	_state = state;
}

-(void)setCountry:(NSString*)country {
	_country = country;
}

- (void) fetchData {
	[[NSTimer scheduledTimerWithTimeInterval:0.75 target:self selector:@selector(buildContent:) userInfo:nil repeats:NO] retain];
	
}


-(void) buildContent:(id)p {
	
	DataManager *dm = [DataManager alloc];
	
	SQLiteDB *sql = [[SQLiteDB alloc] initWithPath:[dm getDataBaseName:_country]];
	
	
	
	
	
	
	
	NSArray *nsa = [sql query:[NSString stringWithFormat:@"select c.city, s.state, z.zipcode, a.add1 from relations r, city c, states s, zipcodes z, addendum1 a where r.cityid = c.id and r.stateid = s.id and r.zipid = z.id and r.add1id = a.id and z.zipcode like '%@' group by r.zipid order by z.zipcode;",_zipcode]];
	//NSLog(@"array: %@",nsa);
	
	_state = [ NSString stringWithFormat: @"%@", [[nsa objectAtIndex:0] objectForKey:@"state"] ];
	[_state retain];
	_addendum1 = [[ NSString stringWithFormat: @"%@", [[nsa objectAtIndex:0] objectForKey:@"add1"] ] capitalizedString] ;
	[_addendum1 retain];
	
	
	//[_zipcodes release];
	_zipcode  = [ NSString stringWithFormat: @"%@", [[nsa objectAtIndex:0] objectForKey:@"zipcode"] ];
	[_zipcode retain];
	
	_city  = [ NSString stringWithFormat: @"%@", [[nsa objectAtIndex:0] objectForKey:@"city"] ];
	[_city retain];
	
	//NSLog(@"city: %@",_city);
	//NSLog(@"state: %@",_state);
	//NSLog(@"country: %@",_country);
	//NSLog(@"add1: %@",_addendum1);
	
	if ([dm isFavouredEntry:_city forCountry:_country]) {
		
		//NSLog(@"fav entry");
		_isfavoured = YES;
		
		[_table setDeletable:13];
		[_table setInsertable:0];
		_favourstr = @"Remove from favourites";
		
		
	}
	
	[sql release];
	[dm release];
	
	[_table reloadData];
	[_uiphud show: NO];
	[_uiphud removeFromSuperview];
	[_uiphud release];
	
}

-(void)setDelegate:(id)del {
	//NSLog(@"delegate: %@",del);
	_delegate = del;
}



-(void)setPrevView:(UIView*)pv {
	_prevView = pv;
}

-(UIView*)getPrevView {
	return _prevView;
}

#pragma mark - delegated methods-

- (int)numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table
{
	return 7;
}


- (float)preferencesTable:(UIPreferencesTable *)table 
			 heightForRow:(int)row 
				  inGroup:(int)group 
	   withProposedHeight:(float)proposed 
{
	if (group == 0 || group == 2) {
        return 10;
    }
	
	
    return proposed;
}


- (int)preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group
{
	switch (group)
  {
	  case 0: return 1;
	  case 1: return 1;
	  case 2:	return 1;
	  case 3: return 1;
	  case 4: return 3;
	  case 5: return 1;
	  case 6: return 1;
		  
  }
}

- (UIPreferencesTableCell *)preferencesTable:(UIPreferencesTable *)table cellForGroup:(int)group
{
	UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
	
	return [cell autorelease];
}

- (UIPreferencesTableCell *)preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group
{
	
	if (group == 0 || group == 2)
	  {
		  
		  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
		  [cell setTitle:@""];
		  [ cell setDrawsBackground: NO ];
		  return [cell autorelease];
	  }				
	else if (group == 1)
	  {
		  
		  
		  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
		  [cell setTitle:_zipcode];
		  [cell setAlignment:2];
		  
		  return [cell autorelease];
		  
		  
		  
	  } 
	else if (group == 4) 
	  {
		  switch (row)
		{
			case 0:
		  {
			  UIPreferencesTableCell *statecell = [[UIPreferencesTableCell alloc] init];
			  [statecell setTitle:@"State"];
			  [statecell setValue:_state];
			  
			  //[statecell setAlignment:citycellAlign];
			  
			  return [statecell autorelease];
		  }
			case 1:
		  {
			  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
			  [cell setTitle:@"Country"];
			  [cell setValue:_country];
			  [cell setUsesBlueDisclosureCircle:YES];
			  
			  return [cell autorelease];
		  }
			case 2:
		  {
			  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
			  [cell setTitle:@"County"];
			  [cell setValue:_addendum1];
			  [cell setUsesBlueDisclosureCircle:YES];
			  
			  return [cell autorelease];
		  }
		}
	  } 
	else if (group == 3) 
	  {
		  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
		  [cell setTitle:@"City"];
		  [cell setValue:[_city capitalizedString]];
		  [cell setUsesBlueDisclosureCircle:YES];
		  
		  return [cell autorelease];
	  }	
	else if (group == 5) 
	  {
		  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
		  [cell setTitle:_favourstr];
		  [cell setAlignment:2];
		  return [cell autorelease];
	  }
	
	else if (group == 6) 
	  {
		  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
		  [cell setTitle:@"Show in Maps"];
		  [cell setShowDisclosure:YES];
		  [cell setAlignment:2];
		  return [cell autorelease];
	  }
	
}

- (void)tableRowSelected:(NSNotification *)notification
{
	
	//NSLog(@"selected: %d",[_table selectedRow]);
	if ([_table selectedRow] == 15)
	  {
		  
		  
		  NSString *urlstring = [NSString stringWithFormat:@"http://maps.google.com/?q=%@ %@ %@",_zipcode, _city,_country];
		  NSString *fixedURL = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)urlstring, NULL, NULL, kCFStringEncodingUTF8);
		  
		  MobileZIPCodesApp *mzca = [MobileZIPCodesApp sharedInstance];
		  
		  [mzca openURL:[NSURL URLWithString:fixedURL]];
	  }	
	
}


- (void)table:(UITable*)table deleteRow:(int)row {
	// the remove code
	//[activesArray removeObject:[NSString stringWithFormat:@"%d",row]];
	//NSLog(@" detelet: %d",row);
	
	_isfavoured = NO;
	
	[_table setDeletable:0];
	[_table setInsertable:13];
	_favourstr = @"Add to favourites";
	
	DataManager *dm = [DataManager alloc];
	
	[dm removeFavouredEntry:_city  forCountry:_country];
	
	[dm release];
	
	
	[_table reloadData];
}


- (void) table:(UITable *) table insertAtRow:(int) row 
{
	//NSLog(@" insertrow: %d",row);
	
	_isfavoured = YES;
	
	[_table setDeletable:13];
	[_table setInsertable:0];
	_favourstr = @"Remove from favourites";
	
	
	DataManager *dm = [DataManager alloc];
	
	[dm addFavouredEntry:_city withState:_state forCountry:_country];
	
	[dm release];
	
	[_table reloadData];
	
    
}


- (BOOL) table:(UITable *) table canSelectRow:(int) row 
{
	if (row == 15) return YES; else return NO;
}



@end
